'''
Created on 09-09-22

@author: peterd
'''

import re
from sgmllib import SGMLParser

class CSEParser(SGMLParser):
	'''
	responsible for parsing CSE result
	'''

	def __init__(self):
		SGMLParser.__init__(self)
		
		self.inResult_ = False
		self.inResultTitle_ = False
		self.resultTitle_ = ''
		self.resultUrl_ = None
		self.inResultContent_ = False
		self.resultContent_ = ''
		
		self.results_ = []


	# return search result stat, searchResult list, page navigation 
	def parse(self, result):
		resultStat = None
		navBar = None
	
		m = re.search('<td align=right nowrap><font size=-1>(.*?)</font>', result)
		if m:
			resultStat = m.group(1)
			
		# TODO: in order to intercept search result, href must be prefixed by link
		# to searchHandler
		m = re.search('<div id=navbar class=n>(.*?)</div>', result)
		if m:
			navBar = re.sub('href=(".*?")', addInterceptor, m.group(1))
			
			
		self.feed(result)
		
		return (resultStat, self.results_, navBar)
		
		
	def start_div(self, attrs):
		for attr, value in attrs:
			if attr == 'class' and value == 'g':
				self.inResult_ = True
				break
			if self.inResult_ and attr == 'class' and value == 'std':
				self.inResultContent_ = True 


	def end_div(self):
		if self.inResult_:
			self.inResult_ = False
		if self.inResultContent_:
			self.inResultContent_ = False
					
			
	def start_a(self, attrs):
		if self.inResult_:
			for attr, value in attrs:
				if attr == 'href':
					self.resultUrl_ = value
					self.inResultTitle_ = True
					break


	def end_a(self):
		if self.inResultTitle_:
			self.inResultTitle_ = False
			

	def start_b(self, attrs):
		if self.inResultContent_:
			self.resultContent_ += '<b>'


	def end_b(self):
		if self.inResultContent_:
			self.resultContent_ += '</b>'
	

	def start_em(self, attrs):
		if self.inResultTitle_:
			self.resultTitle_ += '<em>'
		
		if self.inResultContent_:
			self.resultContent_ += '<em>'


	def end_em(self):
		if self.inResultTitle_:
			self.resultTitle_ += '</em>'
		
		if self.inResultContent_:
			self.resultContent_ += '</em>'


	def start_br(self, attrs):
		if self.inResultContent_:
			self.inResultContent_ = False
			self.results_.append({'title': self.resultTitle_, 'url': self.resultUrl_, 'content': self.resultContent_})
			self.reset__()


	def handle_data(self, data):
		if self.inResultTitle_ and data:
			self.resultTitle_ += data
		if self.inResultContent_ and data:
			self.resultContent_ += data
		
			
			
	def reset__(self):
		self.resultTitle_ = ''
		self.resultContent_ = ''
		
		
#
# helpers
#

def addInterceptor(m):
	url = m.group(1).replace('"', '')
	return 'href="#" onclick="javascript:fetchPage(\'%s\')"' % url


